export default function () {
    function waterfalls(option) {
        const self = this;

        this.dom = $(option.id);

        //resize 配置
        this.resizeConfig = option.resizeConfig;

        //多少列
        this.currentColumnConfig = this.resizeWidth($(window).width()); //option.columns || 3;

        //每列间距
        this.columnsGutter = "20px";

        //渲染方式
        this.renderType = option.renderType || "Js";

        //每行间距
        this.rowGutter = "20px";

        //节点 $(option.id)
        this.fallNode = null;
        //子元素类名
        this.childrenClassName = option.childrenClass || ".mo-waterfall-column";

        //距离底部高度
        this.bottomDistance = option.bottomDistance || 30;

        //渲染方法
        this.render = option.render;

        //获取图片数据key
        this.imgKey = option.imgKey || false;

        //窗口可见高度
        this.windowH = $(window).height();

        //滚动到底部
        this.scrollBottom = option.scrollBottom;

        //渲染完成
        this.renderComplete = option.renderComplete;

        //加载样式
        this.loadHtml = $('<div class="mo-waterfall-status-box"><div class="loading-box"></div></div>');

        //加载所有样式

        // this.allHtml = $('<div class="mo-waterfall-allLoad">价值</div>')

        //数据缓存
        this.storage = [];

        //添加高度
        this.addHeight = option.addHeight;

        //初始化·
        this.initDom();

        //滚动事件监听
        $(window).scroll(function () {
            // const theme_id = moi.getUrlParam("theme_id");
            // if (!theme_id) {
            self.scroll.call(this, self);
            // }
        });

        //页面大小变化监听
        $(window).resize(function () {
            const width = $(window).width();
            const columns = self.resizeWidth(width);
            if (columns && columns.columns !== self.currentColumnConfig.columns) {
                self.refresh(columns);
            }
        });
    }

    //获取宽度布局
    waterfalls.prototype.resizeWidth = function (width) {
        for (let i = 0; i < this.resizeConfig.length; i++) {
            const config = this.resizeConfig[i];
            if (config.min <= width && (width <= config.max || !config.max)) {
                return config;
            }
        }
        return false;
    };

    //重新初始化
    //渲染数据
    waterfalls.prototype.refresh = function (columns) {
        this.currentColumnConfig = columns;
        this.dom.empty();
        this.initDom();
        this.storageRender(this.storage);
    };

    //渲染默认数据
    waterfalls.prototype.RenderDefaultData = function (data, moreText) {
        const list = [];
        for (let index = 0; index < this.currentColumnConfig.columns * 3; index++) {
            list.push(data);
        }
        this.storageRender(list);
        this.showMore(moreText, "javascript:;");
    };

    //初始化dom渲染列
    waterfalls.prototype.initDom = function () {
        this.dom.append(`<div class="mo-waterfall-warp"></div>`);

        this.fallNode = this.dom.children(".mo-waterfall-warp");
        //追加列数据
        for (let i = 0; i < this.currentColumnConfig.columns; i++) {
            const element = $(`<div class="mo-waterfall-column" style="--row-gutter:${this.currentColumnConfig.rowGutter}"></div>`);
            this.fallNode.append(element);
        }

        //设置css 变量属性
        this.fallNode.attr(
            "style",
            `--columns:${this.currentColumnConfig.columns};--column-gutter:${this.currentColumnConfig.columnsGutter}`
        );

        //子元素
        this.childs = this.getChilds();
    };

    //追加数据
    waterfalls.prototype.addStorage = function (data) {
        this.storage = [...this.storage, ...data];
        this.storageRender(data);
    };

    waterfalls.prototype.getImageHeight = function (src, callback, i) {
        if (!src) {
            callback && callback(0);
            return;
        }
        let image = new Image();
        image.src = `${src}?x-oss-process=image/resize,m_lfit,w_100`;
        image.onload = () => {
            const scale = image.height / image.width;
            const proportional = (this.childs.width * scale).toFixed(2);
            callback && callback(Number(proportional));
        };
        image.onerror = () => {
            console.log("加载失败");
            callback && callback(0);
        };
    };

    //渲染数据
    waterfalls.prototype.storageRender = function (list) {
        const loadHtml = [];
        let sotrs = this.getChildsMinHeight();
        let startIndex = 0;
        // console.warn(startIndex)
        for (let i = 0; i < list.length; i++) {
            const index = sotrs[startIndex];
            if (!loadHtml[index]) {
                loadHtml[index] = [];
            }
            list[i]["currentIndex"] = i;
            if (this.renderType === "liquid") {
                loadHtml[index].push(list[i]);
            } else {
                loadHtml[index].push(this.render(list[i]));
            }
            startIndex = startIndex === this.childs.node.length - 1 ? 0 : startIndex + 1;
        }
        this.appendHTml(loadHtml);
    };

    waterfalls.prototype.forAppendHTml = function (loadHtml) {
        for (let i = 0; i < loadHtml.length; i++) {
            this.appendHTml(loadHtml[i].html, loadHtml[i].height);
        }
    };

    //获取瀑布流距离顶部高度
    waterfalls.prototype.getOffsetTop = function () {
        return (this.fallNode.offset() && this.fallNode.offset().top) || 0;
    };

    //获取窗口高度
    waterfalls.prototype.window = function () {
        return $(window).height();
    };

    //获取瀑布流高度
    waterfalls.prototype.getHeight = function () {
        return this.fallNode.height();
    };

    //获取子内容

    waterfalls.prototype.getChilds = function () {
        const node = this.fallNode.children(this.childrenClassName);
        const heights = [];
        for (let i = 0; i < node.length; i++) {
            heights.push({ index: i, height: node.eq(i).height() });
        }
        return {
            node,
            width: node.eq(0).width(),
            heights
        };
    };

    //获取子元素最小的高度
    waterfalls.prototype.getChildsMinHeight = function () {
        const childsHeight = this.childs.heights;
        const copyChildsHeight = JSON.parse(JSON.stringify(childsHeight));
        return copyChildsHeight
            .sort((a, b) => a.height - b.height)
            .map((item) => {
                return item.index;
            });
    };

    //设置高度
    waterfalls.prototype.setHeight = function (index, height) {
        this.childs.heights[index] = this.childs.heights[index] + height + this.addHeight();
    };

    //滚动事件
    waterfalls.prototype.scroll = function (self) {
        //滚动高度
        const scrollTop = $(this).scrollTop();

        if (scrollTop + self.windowH + self.bottomDistance >= self.getHeight() + self.getOffsetTop()) {
            //设置内容高度
            self.childs = self.getChilds();
            //执行回调方法
            self.scrollBottom && self.scrollBottom.call(this);
        }
    };

    waterfalls.prototype.complete = function () {
        moi.bindRedirectHref(this.fallNode.find("a"));
        this.renderComplete && this.renderComplete.call(this, this.fallNode);
    };

    //追加html
    waterfalls.prototype.appendHTml = function (loadHtml) {
        const self = this;
        const childsNode = this.childs.node;
        let completeCount = 0;
        for (let i = 0; i < loadHtml.length; i++) {
            if (loadHtml[i]) {
                //liquid
                if (this.renderType === "liquid") {
                    this.render(loadHtml[i], function (node) {
                        childsNode.eq(i).append(node);
                        self.renderComplete && self.renderComplete.call(this, node);
                        moi.onEvent("waterfallsComplete");
                    });
                } else {
                    //html追加
                    const node = $(loadHtml[i].join(""));
                    childsNode.eq(i).append(node);
                    self.renderComplete && self.renderComplete.call(this, node);
                    moi.onEvent("waterfallsComplete");
                }
            }
        }
    };

    //显示加载
    waterfalls.prototype.showLoad = function () {
        this.dom.append(this.loadHtml);
    };

    //隐藏
    waterfalls.prototype.hideLoad = function () {
        this.loadHtml.remove();
    };

    //显示加载完毕
    waterfalls.prototype.showAll = function (text) {
        this.dom.append($(`<div class="mo-waterfall-status-box"><span>${text}</span></div>`));
    };

    //显示加载更多
    waterfalls.prototype.showMore = function (text, href) {
        if (text) {
            this.dom.append($(`<div class="mo-waterfall-status-box"><a href='${href}' class="secondary_btn">${text}</a></div>`));
        }
    };

    window["waterfalls"] = waterfalls;
}
